package vn.edu.ptithcm.pim.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang.ArrayUtils;

public class PimUtil {
	public static void writeLog(String s) throws IOException {
		StringBuilder sb = new StringBuilder();
		BufferedWriter bw = new BufferedWriter(new FileWriter("C:/pim-log.txt",
				true));
		sb.append("\n");
		sb.append(new Date().toString() + "  :  ");
		sb.append(s + "\n");
		bw.write(sb.toString());
		bw.close();
	}

	public static void writeFile(String fileName, List<String> fileContent,
			String _enc) throws IOException {
		BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
				new FileOutputStream(fileName), _enc));
		Iterator<String> it = fileContent.iterator();
		while (it.hasNext()) {
			out.write(it.next());
			out.newLine();
		}
		out.flush();
		out.close();
	}

	public static List<String> readFile(String fileName, String _enc)
			throws IOException {
		BufferedReader in = new BufferedReader(new InputStreamReader(
				new FileInputStream(fileName), _enc));
		List<String> lines = new ArrayList<String>();
		String line = "";
		while ((line = in.readLine()) != null) {
			lines.add(line);
		}
		in.close();
		return lines;
	}

	public static int generate(int min, int max, int[] numbers) {
		if (numbers.length == 0) {
			return min + (int) (Math.random() * ((max - min) + 1));
		}

		int number = 0;
		do {
			number = min + (int) (Math.random() * ((max - min) + 1));
		} while (ArrayUtils.contains(numbers, number));

		return number;
	}
}
